package com.tio.im.client;

import com.tio.im.common.Const;
import com.tio.im.common.ShowcasePacket;
import com.tio.im.common.Type;
import com.tio.im.common.packets.GroupMsgReqBody;
import com.tio.im.common.packets.P2PReqBody;
import org.tio.client.AioClient;
import org.tio.client.ClientChannelContext;
import org.tio.client.ClientGroupContext;
import org.tio.client.ReconnConf;
import org.tio.client.intf.ClientAioHandler;
import org.tio.client.intf.ClientAioListener;
import org.tio.core.Aio;
import org.tio.core.Node;
import org.tio.json.Json;

/**
 *	点对点聊天
 * @author tanyaowu
 */
public class P2pMsgClientStarter {
	static String serverIp = "127.0.0.1";
	static int serverPort = Const.PORT;

	private static Node serverNode = new Node(serverIp, serverPort);

	//用来自动连接的，不想自动连接请设为null
	private static ReconnConf reconnConf = new ReconnConf(5000L);

	private static ClientAioHandler aioClientHandler = new ShowcaseClientAioHandler();
	private static ClientAioListener aioListener = new ShowcaseClientAioListener();
	private static ClientGroupContext clientGroupContext = new ClientGroupContext(aioClientHandler, aioListener, reconnConf);

	private static AioClient aioClient = null;

	static ClientChannelContext clientChannelContext;

	public static void main(String[] args) throws Exception {
		aioClient = new AioClient(clientGroupContext);
		clientChannelContext = aioClient.connect(serverNode);
        clientChannelContext.setUserid("261586d3-498d-48c7-a5c0-2cc9680c4af6");

		command();
	}

	public static void command() throws Exception {
		String toUserid = "261586d3-498d-48c7-a5c0-2cc9680c4af7";
		String text = "你好，我是-----------1";
		while (true){
			Thread.sleep(2000);
			processCommand(toUserid, text);
		}

//		aioClient.stop();
//		System.exit(0);
	}

	public static void processCommand(String toUserid, String text) throws Exception {
		P2PReqBody p2pReqBody = new P2PReqBody();
		p2pReqBody.setToUserid(toUserid);
		p2pReqBody.setText(text);

		ShowcasePacket reqPacket = new ShowcasePacket();
		reqPacket.setType(Type.P2P_REQ);
		reqPacket.setBody(Json.toJson(p2pReqBody).getBytes(ShowcasePacket.CHARSET));

		Aio.send(clientChannelContext, reqPacket);
	}
}
